package cn.client.ui.view.main.chat.friend

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.client.data.remoteData.bean.BaseResp
import cn.client.data.remoteData.bean.FriendCardItem
import cn.client.data.remoteData.bean.FriendInfo
import cn.client.data.remoteData.bean.SearchFriendRes
import cn.client.data.remoteData.bean.UploadNickname
import cn.client.data.localData.dao.UserDao
import cn.client.data.remoteData.repository.FriendRepository
import cn.client.ui.view.main.user.UserInfoViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class FriendViewModel @Inject constructor(
    private val repository: FriendRepository,
    private val userDao: UserDao
) : ViewModel() {

    /**
     * 事件管道
     */
    private val _pageEvents = Channel<PageEvent>(Channel.BUFFERED)

    /**
     * 可观察事件数据流
     */
    val pageEvents = _pageEvents.receiveAsFlow()

    /**
     * 可变状态
     */
    var pageStates by mutableStateOf(PageState())
        private set

    // 使用MutableStateFlow来存储好友列表
    private val _friendList = MutableStateFlow<List<FriendCardItem>>(emptyList())
    val friendList: StateFlow<List<FriendCardItem>> = _friendList

    // 使用MutableStateFlow来存储好友信息
    private val _friendInfoRes = MutableStateFlow<FriendInfo?>(null)
    val friendInfoRes: StateFlow<FriendInfo?> = _friendInfoRes

    /**
     * 收集意图
     */
    fun dispatch(intent: PageIntent){
        when(intent) {
            is PageIntent.GetUser -> getUser(intent.msg)
            is PageIntent.FriendList -> getFriendList(intent.uid)
            is PageIntent.FriendInfo -> getFriendInfo(intent.fid)
            is PageIntent.UpdateNickname -> updateNickname(intent.uid, intent.fid, intent.nickname)
            else -> {Unit}
        }
    }

    // 获取好友列表
    private fun getFriendList(uid: Int){
        viewModelScope.launch {
            try {
                val res = repository.friendList(uid)
                if (res.code==200){
                    _friendList.value = res.data ?: emptyList()
//                    _pageEvents.send(PageEvent.FriendList(res))
                } else {
                    val err = res.msg
                    _pageEvents.send(PageEvent.Error(err))
                    Log.d("FriendViewModel","获取失败：$err")
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("FriendViewModel","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 获取好友信息
    private fun getFriendInfo(fid: Int){
        viewModelScope.launch {
            try {
                val res = repository.friendInfo(fid)
                if (res.code==200){
                    _friendInfoRes.value = res.data
//                    _pageEvents.send(PageEvent.FriendInfo(res))
                } else {
                    val err = res.msg
                    _pageEvents.send(PageEvent.Error(err))
                    Log.d("FriendViewModel","获取失败：$err")
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("FriendViewModel","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 修改好友备注
    private fun updateNickname(uid: Int, fid: Int, nickname: String){
        viewModelScope.launch {
            val uploadNickname = UploadNickname(uid, fid, nickname)
            try {
                val res = repository.updateNickname(uploadNickname)
                if (res.code==200){
                    _pageEvents.send(PageEvent.UpdateNickname(res))
                } else {
                    val err = res.msg
                    _pageEvents.send(PageEvent.Error(err))
                    Log.d("FriendViewModel","修改失败：$err")
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("FriendViewModel","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }



    /**
     * 查询本地缓存
     */
    private fun getUser(msg: String){
        Log.d("getUser","消息：$msg")
        viewModelScope.launch {
            userDao.getUser().catch { e ->
                Log.d("FriendViewModel", "错误：$e")
                _pageEvents.send(PageEvent.GetErr("错误：$e"))
            }.collect { it ->
                if (it != null) {
                    _pageEvents.send(PageEvent.UserRes(uid = it.uid))
                } else {
                    _pageEvents.send(PageEvent.GetErr("查询失败"))
                }
            }
        }
    }


    /**
     * 意图集
     */
    sealed class PageIntent {
        data class GetUser(val msg: String) : PageIntent()  // 查询本地缓存

        data class FriendList(val uid: Int): PageIntent()
        data class FriendInfo(val fid: Int): PageIntent()
        data class UpdateNickname(val uid: Int, val fid: Int, val nickname: String): PageIntent()
    }

    /**
     * 事件集
     */
    sealed class PageEvent {
        object Idle: PageEvent()
        data class FriendList(val res: BaseResp<List<FriendCardItem>>): PageEvent() // 好友列表
        data class FriendInfo(val res: BaseResp<cn.client.data.remoteData.bean.FriendInfo>): PageEvent() //好友详情信息
        data class UpdateNickname(val res: BaseResp<Any>): PageEvent() //修改好友昵称
        data class UserRes(val uid: Int) : PageEvent()  // 本地缓存
        data class GetErr(val msg: String): PageEvent() // 获取本地缓存失败
        data class Error(val error: String): PageEvent()
    }

    /**
     * 状态集
     */
    data class PageState(
        val uid: Int = -1
    )

}